package graduation.controller;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import graduation.entity.User;
import graduation.service.UserService;
import graduation.utils.FileUtilt;
import graduation.utils.Md5Utils;
import graduation.utils.ResultVOUtil;
import graduation.vo.PageVO;
import graduation.vo.ResultVO;

@Controller
@RequestMapping("/user")
public class UserContrller {
	@Autowired
	private UserService userServiceImpl;

	@RequestMapping(value = "login", method = RequestMethod.POST) // 用来处理请求地址映射的注解
	@ResponseBody // @Responsebody 注解表示该方法的返回的结果直接写入 HTTP 响应正文（ResponseBody）中
	public ResultVO loginByPhone(@RequestParam("phoneOrEmail") String phoneOrEmail,
			@RequestParam("password") String password) {
		User user = null;
		// 判断密码是否正确
		// 获取密码
		String pws = Md5Utils.getMd5(password);
		// 判断是电话号码还是电子邮箱
		if (phoneOrEmail.indexOf("@") != -1) {
			// 判断为邮箱
			// 通过email查询数据库是否存在该账号，不存在则返回表示没有该用户
			user = userServiceImpl.findByEmail(phoneOrEmail);
			System.out.println(phoneOrEmail);
			System.out.println(user);
			if (user == null) {
				System.out.println(user == null);
				return ResultVOUtil.fail("没有邮箱账号");
			}

			System.out.println(pws);
			// 不相等返回登录失败
			if (!pws.equals(user.getPassword())) {
				return ResultVOUtil.fail("密码错误");
			}

		} else {
			// 通过电话号码查询数据库是否存在该账号，不存在则返回表示没有该用户
			user = userServiceImpl.findByPhone(phoneOrEmail);
			if (user == null) {
				return ResultVOUtil.fail("没有该用手机账号");
			}
			// 判断密码是否正确
			// String pws = Md5Utils.getMd5(password);
			// 不相等返回登录失败
			if (!pws.equals(user.getPassword())) {
				return ResultVOUtil.fail("密码错误");
			}

		}

		return ResultVOUtil.success("登录成功", user);

	}

	@RequestMapping(value = "getAllUser", method = RequestMethod.GET)
	@ResponseBody
	public ResultVO getAllUser(int page, int size) {

		PageVO pageMessage = userServiceImpl.getAllUser(page, size);
		System.out.println(pageMessage);
		return ResultVOUtil.success(pageMessage);
	}

	/**
	 * 注册
	 * 
	 * @param name
	 * @param email
	 * @param phone
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "register", method = RequestMethod.POST)
	@ResponseBody
	public ResultVO register(@RequestBody User user) {
		// 查询是否有相同的邮箱和手机号码
		System.out.println(user);

		if (userServiceImpl.findByEmail(user.getEmail()) != null) {
			return ResultVOUtil.fail("邮箱已被注册");
		}
		// ;
		if (userServiceImpl.findByPhone(user.getPhone()) != null) {
			return ResultVOUtil.fail("手机号码已被注册");
		}
		// md5加密
		String psw = Md5Utils.getMd5(user.getPassword());
		// 获取随机不重复id
		String userId = UUID.randomUUID().toString();
		userId = userId.replace("-", "");
		System.out.println(userId);
		user.setId(userId);
		user.setPassword(psw);
		// User user1 = new User();
		// user1.setId(userId);
		// user1.setPassword(psw);
		// 保存到数据库
		userServiceImpl.addUser(user);
		System.out.println(user);
		return ResultVOUtil.success(user);
	}

	/**
	 * 删除用户
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "delUserById",method = RequestMethod.POST)
	@ResponseBody
	public ResultVO delUserById(@RequestBody Map<String, Object> map) {
		String userId = map.get("userId").toString();
		System.out.println("userId"+userId);
		System.out.println(userId);
		User user = userServiceImpl.findUserById(userId);
		System.out.println(user);
		userServiceImpl.delUser(user);
		return ResultVOUtil.success("删除成功");

	}

	/**
	 * 通过姓名模糊查询
	 * 
	 * @param name
	 * @return
	 */
	@RequestMapping(value = "findUserByName", method = RequestMethod.GET)
	@ResponseBody
	public ResultVO findUserByName(String name) {
		List<User> list = userServiceImpl.findUserByName(name);
		if (list == null) {
			return ResultVOUtil.fail("查无此人");
		}
		return ResultVOUtil.success(list);

	}

	/**
	 * 修改信息
	 * 
	 * @param name
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "updateUserById")
	@ResponseBody
	public ResultVO updateUserById(@RequestBody User user) {
		System.out.println("user" + user);
		// 通过id查询
		User userByFind = userServiceImpl.findUserById(user.getId());
		System.out.println("userByFind" + userByFind);
//		String pws = Md5Utils.getMd5(user.getPassword());
		if (userByFind == null) {
			return ResultVOUtil.fail("用户不存在");
		}
		// 不为空就存到数据中
		if (user.getName() != null) {
			userByFind.setName(user.getName());
		}
		if (user.getPassword() != null) {
//			userByFind.setPassword();
		}
		if (user.getEmail() != null && !userByFind.getEmail().equals(user.getEmail())) {

			if (userServiceImpl.findByEmail(user.getEmail()) == null) {
				userByFind.setEmail(user.getEmail());
			} else {
				return ResultVOUtil.fail("该邮箱已被使用");
			}

		}
		if (user.getGender() != null) {
			if ("男".equals(user.getGender()) || "女".equals(user.getGender())) {
				userByFind.setGender(user.getGender());
			} else {
				return ResultVOUtil.fail("性别错误");
			}

		}
		if (user.getBirth() != null) {
			userByFind.setBirth(user.getBirth());
		}
		if (user.getPhone() != null && !userByFind.getPhone().equals(user.getPhone())) {
			System.out.println(userServiceImpl.findByPhone(user.getPhone()));
			if (userServiceImpl.findByPhone(user.getPhone()) == null) {
				System.out.println(userServiceImpl.findByPhone(user.getPhone()));
				userByFind.setPhone(user.getPhone());
			} else {
				return ResultVOUtil.fail("该号码已被使用");
			}

		}
		if (user.getQQ() != null) {
			userByFind.setQQ(user.getQQ());
		}
		if (user.getWechat() != null) {
			userByFind.setWechat(user.getWechat());
		}
		if (user.getAddress() != null) {
			userByFind.setAddress(user.getAddress());
		}
		if (user.getIntroduction() != null) {
			userByFind.setIntroduction(user.getIntroduction());
		}
		if (user.getHiredate() != null) {
			userByFind.setHiredate(user.getHiredate());
		}
		// 保存到数据库
		userServiceImpl.updateUser(userByFind);
		System.out.println(ResultVOUtil.success("修改成功", user));
		return ResultVOUtil.success("修改成功", user);

	}

	/**
	 * 通过id查询用户所有信息
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "getUserById", method = RequestMethod.GET)
	@ResponseBody
	public ResultVO getUserById(String userId) {
		User user = userServiceImpl.findUserById(userId);
		if (user == null) {
			return ResultVOUtil.fail("查无此人");
		}
		return ResultVOUtil.success(user);

	}

	/**
	 * 修改头像
	 * 
	 * @param name
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "updateHeadphoto")
	@ResponseBody
	public ResultVO updateHeadphoto(String userId, MultipartFile headphoto, HttpServletRequest request) {
		System.out.println("123");
		User user = userServiceImpl.findUserById(userId);
		// 文件原始名称（上传前的名字）
		String originalFileName = headphoto.getOriginalFilename();
		// 图片到服务器的名称
		String urlFileName = String.valueOf(new Date().getTime()) + originalFileName;
		// 获取文件类型
		String contentType = headphoto.getContentType();
		// 前半部分路径，目录，将WebRoot下的一个名称为Files文件夹转换成绝对路径
		 String leftPath = request.getSession().getServletContext().getRealPath("/Files/");
		 System.out.println("前半部分路径"+leftPath);
		 System.out.println("文件类型"+contentType);
		// 先判断是否为图片(如果不包含必定全部返回值为-1)
		if (contentType.indexOf("image") == -1) {
			return ResultVOUtil.fail("图片格式错误");
		}

		// //把磁盘上的文件删除
		// try {
		// FileUtilt.DeleteFile(filePath,
		// user.getHeadphoto().substring(user.getHeadphoto().lastIndexOf("/")+1));
		// System.out.println("删除成功");
		// } catch (Exception e1) {
		// // TODO Auto-generated catch block
		// e1.printStackTrace();
		// }
		//

		/*
		 * 本地的映射资源 /attachments/**
		 */
		try {
			FileUtilt.uploadFile(headphoto.getBytes(), leftPath, urlFileName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 图片的地址
		String photoUrl = "/graduation" + "/attachments/" + urlFileName;
		user.setHeadphoto(photoUrl);
		// 保存到数据库
		userServiceImpl.updateUser(user);
		return ResultVOUtil.success(photoUrl);

	}
}
